import _ from 'lodash';
import moment from 'moment';
import * as taskService from '../services/taskService';

const TASK_TYPE = 101;

export default {
  namespace: 'customizeTask',
  state: {
    taskList: [],
    vipList: [],
  },
  effects: {
    * fetchTaskList({ payload }, { call, put, select }) {
      const { shopId, branchNo } = yield select(state => state.auth.currentUser);
      const result = yield call(taskService.customizeTaskList, shopId);
      yield put({ type: 'saveTaskList', payload: result.data });
      if (result.data && result.data.length) {
        for (const task of result.data) {
          yield put({
            type: 'task/fetchVips',
            payload: {
              taskType: TASK_TYPE,
              subType: task.taskId,
              pageSize: 100,
            },
          });
        }
      }
    },
    * fetchVipList({ payload: { month, keywords } }, { call, put, select }) {
      const { shopId, branchNo, salemanId } = yield select(state => state.auth.currentUser);
      const result = yield call(taskService.customizeTaskVipList, shopId, branchNo, salemanId, month, keywords);
      yield put({ type: 'saveVipList', payload: result.data });
    },
  },
  reducers: {
    saveItems(state, { payload }) {
      return { ...state, tasks: payload };
    },
    saveTaskList(state, { payload }) {
      return { ...state, taskList: payload };
    },
    saveVipList(state, { payload }) {
      return { ...state, vipList: payload };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => {
        if (pathname === '/p101') {
          dispatch({
            type: 'fetchTaskList',
          });
        }
      });
    },
  },
};
